package com.ice.app;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.druid.support.http.StatViewServlet;

/**
 * CMS SpringBoot版
 */
//改变自动扫描的包
@ComponentScan(basePackages = { "com.iceframework.**", "com.ice.app.**" })
@MapperScan("com.ice.app.*.mapper")
@SpringBootApplication(exclude = { org.activiti.spring.boot.SecurityAutoConfiguration.class })
public class AdminBootstrap extends SpringBootServletInitializer implements WebMvcConfigurer {

	// druid用户名
	@Value("${spring.datasource.username}")
	private String username;
	// druid密码
	@Value("${spring.datasource.password}")
	private String password;

	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * 初始化方法 order为执行顺序
	 * 
	 * @throws SchedulerException
	 */
	@PostConstruct
	@Order(1)
	public void postConstruct() throws Exception {
		logger.info("----------------------- Init System Resource -----------------------");
		// 初始化资源放在这里
		logger.info("-----------------------     Init Succeed     -----------------------");
	}

	/**
	 * 德鲁伊的监控
	 * 
	 */
	@Bean
	public ServletRegistrationBean<StatViewServlet> druidServletRegistration() {
		logger.info("----------------------- 开启德鲁伊监控 -----------------------");
		ServletRegistrationBean<StatViewServlet> registration = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet());
		registration.addUrlMappings("/druid/*");
		registration.addInitParameter("loginUsername", username);
		registration.addInitParameter("loginPassword", password);
		return registration;
	}

	public static void main(String[] args) {
		SpringApplication.run(AdminBootstrap.class, args);
	}

	/**
	 * 打war包用
	 */
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		// 注意这里要指向原先用main方法执行的Application启动类
		return builder.sources(AdminBootstrap.class);
	}

	@Primary
	@Bean
	public TaskExecutor primaryTaskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		return executor;
	}

}